package com.liang.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
public class CommonController {
    @Autowired
    private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
 
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("/mail") public Object
	 * sendMail03(@RequestParam("username")String username){ int res =
	 * JOptionPane.showConfirmDialog(null, "是否继续发送邮件", "是否继续",
	 * JOptionPane.YES_NO_OPTION); if (res != JOptionPane.YES_OPTION) { return
	 * "邮件发送失败"; // 点击“否”后执行这个代码块 } else { // 点击“是”后执行这个代码块 } MimeMessage
	 * mMessage=javaMailSender.createMimeMessage();//创建邮件对象 MimeMessageHelper
	 * mMessageHelper; Properties prop = new Properties(); String from; try {
	 * //从配置文件中拿到发件人邮箱地址
	 * prop.load(this.getClass().getResourceAsStream("/mail.properties")); from =
	 * prop.get("mail.smtp.username")+""; mMessageHelper=new
	 * MimeMessageHelper(mMessage,true); mMessageHelper.setFrom(from);//发件人邮箱
	 * mMessageHelper.setTo("286221628@qq.com");//收件人邮箱
	 * mMessageHelper.setSubject(username+":点击注册成功");//邮件的主题
	 * mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" +
	 * "<a href='https://gitee.com/gorillaceoo'>打开我的git主页</a><br/>" +
	 * "<img src='cid:fengye'>",true);//邮件的文本内容，true表示文本以html格式打开 File file=new
	 * File("C:/Users/chenfeng/Desktop/回主页.JPG");//在邮件中添加一张图片 FileSystemResource
	 * resource=new FileSystemResource(file); mMessageHelper.addInline("fengye",
	 * resource);//这里指定一个id,在上面引用 mMessageHelper.addAttachment("枫叶.png",
	 * resource);//在邮件中添加一个附件 javaMailSender.send(mMessage);//发送邮件 } catch
	 * (MessagingException e) { e.printStackTrace(); } catch (IOException e) {
	 * e.printStackTrace(); } return "发送成功"; } }
	 */
    @RequestMapping("/mail")
    public String sendMail03(@RequestParam("to")String to,@RequestParam("subject")String subject,@RequestParam("text")String text,
    		@RequestParam(value = "file",required = false)CommonsMultipartFile file,HttpServletRequest request) throws IOException {
    	System.out.println(to+","+subject+","+text+","+file.getOriginalFilename());
//    	System.out.println(file.getAbsolutePath());
//    	System.out.println(file.getCanonicalPath());
//    	System.out.println(file.getPath());
    	int res = JOptionPane.showConfirmDialog(null, "是否继续发送邮件", "是否继续", JOptionPane.YES_NO_OPTION);
    	if (res != JOptionPane.YES_OPTION) {
    		request.setAttribute("subjectValue", subject);
    		request.setAttribute("textValue", text);
			return "main";	// 点击“否”后执行这个代码块
    	} else {
    		// 点击“是”后执行这个代码块 }
    		MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
    		MimeMessageHelper mMessageHelper;
    		Properties prop = new Properties();
    		String from;
    		try {
    			//从配置文件中拿到发件人邮箱地址
    			prop.load(this.getClass().getResourceAsStream("/mail.properties"));
    			from = prop.get("mail.smtp.username")+"";
    			mMessageHelper=new MimeMessageHelper(mMessage,true);
    			mMessageHelper.setFrom(from);//发件人邮箱
    			mMessageHelper.setTo(to);//收件人邮箱
    			mMessageHelper.setSubject(subject);//邮件的主题
    			if(file==null||"".equals(file.getOriginalFilename())) {
    				mMessageHelper.setText(text,true);//邮件的文本内容，true表示文本以html格式打开
    				javaMailSender.send(mMessage);
    				request.setAttribute("pic", "不不不带图片的邮件发送成功");
    				return "main";
    			}
    			System.out.println(file.getOriginalFilename());
    			String suffix=file.getOriginalFilename().split("\\.")[1];
    			System.out.println(suffix);
    			if(suffix.equals("JPG")||suffix.equals("JPEG")||suffix.equals("BMP")||suffix.equals("GIF")) {
    				text+="<br/><a href='https://gitee.com/gorillaceoo'>打开猩总的git主页</a><br/><img src='cid:fengye'>";
	    			mMessageHelper.setText(text,true);//邮件的文本内容，true表示文本以html格式打开
	    			String fileUpload1 = fileUpload1(file);
	    			System.out.println(fileUpload1);
	    			File file1 = new File(fileUpload1);
	    			FileSystemResource resource=new FileSystemResource(file1);
	    			mMessageHelper.addInline("fengye",resource);//这里指定一个id,在上面引用
	    			mMessageHelper.addAttachment("枫叶.png",resource);//在邮件中添加一个附件
	    			javaMailSender.send(mMessage);//发送邮件
    				request.setAttribute("pic", "带图片的邮件发送成功");
    				return "main";
    			}
    			request.setAttribute("pic", "上传的图片格式错误，只允许JPG,JPEG,BMP,GIF");
				return "main";
    		} catch (MessagingException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return "main";
    	}
    }
	
	public String fileUpload1(@RequestParam("file")CommonsMultipartFile file) throws IOException {
		String uploadFileName=file.getOriginalFilename();//获取文件名
		//上传路径保存设置
		String path="D:/upload";
		//如果路径不存在，创建一个
		File realPath=new File(path);
		if(!realPath.exists()) {
			realPath.mkdir();
		}
		System.out.println("上传文件保存地址："+realPath);
		InputStream is=file.getInputStream();//文件输入流
		OutputStream os=new FileOutputStream(new File(realPath,uploadFileName));//文件输出流
		//读取写出
		int len=0;
		byte[] buffer=new byte[1024];
		while((len=is.read(buffer))!=-1) {
			os.write(buffer,0,len);
			os.flush();
		}
		os.close();
		is.close();
		String sssss=realPath+"\\"+uploadFileName;
		return sssss;
	}
	
	
	

	@RequestMapping("/upload")
	public String fileUpload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException {
		String uploadFileName=file.getOriginalFilename();//获取文件名
		System.out.println(uploadFileName);
		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getStorageDescription());
		//如果文件名为空，直接回到首页
		if("".equals(uploadFileName)) {
			request.setAttribute("file", "文件名为空，请选择文件");
			return "main";
		}
		System.out.println("上传文件名："+uploadFileName);
		//上传路径保存设置
		String path=request.getServletContext().getRealPath("/upload");
		//如果路径不存在，创建一个
		File realPath=new File(path);
		if(!realPath.exists()) {
			realPath.mkdir();
		}
		System.out.println("上传文件保存地址："+realPath);
		InputStream is=file.getInputStream();//文件输入流
		OutputStream os=new FileOutputStream(new File(realPath,uploadFileName));//文件输出流
		//读取写出
		int len=0;
		byte[] buffer=new byte[1024];
		while((len=is.read(buffer))!=-1) {
			os.write(buffer,0,len);
			os.flush();
		}
		os.close();
		is.close();
		return "main";
	}
	@RequestMapping("/download")
	public String downloads(HttpServletResponse response,HttpServletRequest request) throws Exception {
		//要下载的图片地址
		String path="D:/upload";
		String path1=request.getServletContext().getRealPath("/upload");
		String fileName="回主页啊.JPG";
		//1.设置response 响应头
		response.reset();//设置页面不缓存，情况buffer
		response.setCharacterEncoding("UTF-8");//字符编码
		response.setContentType("multipart/form-data");//二进制传输数据
		//设置响应头
		response.setHeader("content-Disposition",
				"attachment;fileName="+URLEncoder.encode(fileName,"UTF-8"));
		File file=new File(path,fileName);
		//2.读取文件--输入流
		InputStream input=new FileInputStream(file);
		//3.写出文件--输出流
		OutputStream out=response.getOutputStream();
		byte[] buff=new byte[1024];
		int index=0;
		//4.执行 写出操作
		while((index=input.read(buff))!=-1) {
			out.write(buff,0,index);
			out.flush();
		}
		out.close();
		input.close();
		return null;
	}
}

















